package com.fubowen.lepton.ui.search

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.fubowen.lepton.R
import com.fubowen.lepton.conf.SiteConfigViewModel
import com.fubowen.lepton.conf.WebPageConfig
import com.fubowen.lepton.databinding.FragmentSearchListBinding
import com.fubowen.lepton.engine.ISearchEngine
import com.fubowen.lepton.engine.impl.BingSearchEngine
import com.fubowen.lepton.ui.search.recycler.Search
import com.fubowen.lepton.ui.search.recycler.SearchAdapter
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch


private const val TITLE = "title"
private const val URL = "url"

class SearchListFragment : Fragment(R.layout.fragment_search_list) {

    private var title = ""
    private var url = ""
    private var isLoadingData = false
    private var resultList = ArrayList<Search>()
    private val viewModel: SiteConfigViewModel by activityViewModels()

    private lateinit var binding: FragmentSearchListBinding
    private lateinit var recycler: RecyclerView
    private lateinit var adapter: SearchAdapter
    private lateinit var searchEngine: ISearchEngine

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        arguments?.let { args ->
            args.getString(TITLE)?.let {
                title = it
            }
            args.getString(URL)?.let {
                url = it
            }
        }
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        binding = FragmentSearchListBinding.inflate(inflater, container, false)
        searchEngine = BingSearchEngine()
        if (!searchEngine.isEnable) {
            return binding.root
        }
        recycler = binding.viewSearchResult
        adapter = SearchAdapter()
        adapter.setOnClickListener(object : SearchAdapter.OnClickListener {
            override fun onItemClick(view: View?) {
                val linearLayout = recycler.layoutManager as LinearLayoutManager
                view?.let {
                    val position = linearLayout.getPosition(view)
                    val item = resultList[position]
                    item.url?.let { url ->
                        val webPageConfig = WebPageConfig(
                            url = url,
                            title = item.title
                        )
                    }
                }
            }
        })
        recycler.adapter = adapter
        recycler.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                val linearLayout = recyclerView.layoutManager as LinearLayoutManager
                if (dy > 0 && !isLoadingData) {
                    val visibleCount = recyclerView.childCount
                    val total = linearLayout.itemCount
                    val topOffset = linearLayout.findFirstVisibleItemPosition()
                    if ((total - visibleCount - topOffset) <= 5) {
                        getSearchResult()
                    }
                }
            }
        })
        getSearchResult()
        return binding.root
    }

    fun getSearchResult() {
        isLoadingData = true
        CoroutineScope(Dispatchers.IO).launch {
            searchEngine.getSearchResultFlow(url).collect {
                recycler.post {
                    resultList.add(it)
                    adapter.submitList(resultList.toList()) { isLoadingData = false }
                }
            }
        }
    }
}